package com.sskj.givecoin.common;

import android.app.Activity;
import android.app.Application;
import android.content.Intent;
import android.os.Bundle;

import com.lzy.okgo.OkGo;
import com.sskj.givecoin.MyAppLication;
import com.sskj.givecoin.utils.LanguageUtil;
import com.sskj.givecoin.utils.SPUtils;
import com.sskj.givecoin.v.activity.SecurityVerifyActivity;

/**
 * Created by lvzhihao on 17-5-25.
 */

public class BaseActivityLifecycleCallbacks implements Application.ActivityLifecycleCallbacks {
    private boolean isRunInBackground;
    private int appCount;

    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
        AppManager.getAppManager().addActivity(activity);
        if (!LanguageUtil.isSameWithSetting(activity)) {
            LanguageUtil.changeAppLanguage(activity,
                    LanguageUtil.getAppLocale(activity), true);

        }
        if (!LanguageUtil.isSameWithSetting(App.INSTANCE)) {
            LanguageUtil.changeAppLanguage(App.INSTANCE,
                    LanguageUtil.getAppLocale(App.INSTANCE), true);
        }

    }

    @Override
    public void onActivityStarted(Activity activity) {
        appCount++;
        if (isRunInBackground) {
            //应用从后台回到前台 需要做的操作
            back2App(activity);
        }
    }

    @Override
    public void onActivityResumed(Activity activity) {

    }

    @Override
    public void onActivityPaused(Activity activity) {

    }

    @Override
    public void onActivityStopped(Activity activity) {
        appCount--;
        if (appCount == 0) {
            //应用进入后台 需要做的操作
            leaveApp(activity);
        }
    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

    }

    @Override
    public void onActivityDestroyed(Activity activity) {
        AppManager.getAppManager().finishActivity(activity);

        OkGo.getInstance().cancelTag(activity);


    }

    /**
     * 从后台回到前台需要执行的逻辑
     *
     * @param activity
     */
    private void back2App(Activity activity) {
        isRunInBackground = false;
        if ("SplashActivity".equals(activity.getClass().getSimpleName())
                || "RegisterActivity".equals(activity.getClass().getSimpleName())
                || "LoginActivity".equals(activity.getClass().getSimpleName())) {
            return;
        }
        if (MyAppLication.isLogin()) {
            boolean aBoolean = (boolean) SPUtils.get(MyAppLication.getApplication(), MyAppLication.getUId(), false,"");
            if (aBoolean) {//判断是否开启指纹验证
                Intent intent = new Intent(activity, SecurityVerifyActivity.class);
                activity.startActivity(intent);
            }
        }
    }

    /**
     * 离开应用 压入后台或者退出应用
     *
     * @param activity
     */
    private void leaveApp(Activity activity) {
        isRunInBackground = true;
    }
}
